package com.example.woke1;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.zhongcai.online.R;
import com.woke.adapter.Mygridadter1;
import com.woke.diyview.MyGridView;
import com.woke.method.MyApp;
import com.woke.method.UploadImage;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyfaqichildActivity extends Activity implements OnItemClickListener {

	private MyGridView mGridView;
	private Mygridadter1 adapter;
	private String photoPath = "/sdcard/zhongcai/";
	private String photoName = "";
	private static final int PHOTO_CAPTURE = 0x11;
	Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
	private ArrayList<String> maplist = new ArrayList<String>();
	private String stradd = "addmap";
	private MyApp application;
	private String name,money,content;
	private Intent intent;
	private int number;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myfaqichild);
		
		intview();
		
	}

	private void intview() {
		intent = getIntent();
		number = intent.getIntExtra("number", 0);
		findViewById(R.id.myfaqichild_image_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		LayoutInflater inflater = getLayoutInflater();
		maplist.add(stradd);
		application = (MyApp) getApplication();
		mGridView = (MyGridView) findViewById(R.id.myfaqichild_gridview);
		adapter = new Mygridadter1(inflater,maplist,application.screenWidth,MyfaqichildActivity.this);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
		final EditText mEname = (EditText) findViewById(R.id.myfaqichild_edit_name);
		final EditText mEmoney = (EditText) findViewById(R.id.myfaqichild_edit_money);
		final EditText mEcontent = (EditText) findViewById(R.id.myfaqichild_edit_content);
		findViewById(R.id.myfaqichild_text_baocun).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				name = ""+mEname.getText().toString().trim();
				money = ""+mEmoney.getText().toString().trim();
				content =""+ mEcontent.getText().toString().trim();
				if(name.equals("")){
					Toast.makeText(MyfaqichildActivity.this, "请输入项目名称", Toast.LENGTH_SHORT).show();
				}else if(money.equals("")){
					Toast.makeText(MyfaqichildActivity.this, "请输入支持金额", Toast.LENGTH_SHORT).show();
				}else if(content.equals("")){
					Toast.makeText(MyfaqichildActivity.this, "请输入项目介绍", Toast.LENGTH_SHORT).show();
				}else if(maplist.size() < 2){
					Toast.makeText(MyfaqichildActivity.this, "至少选择一张图片", Toast.LENGTH_SHORT).show();
				}else{
					if(maplist.size() < 4){
						maplist.remove(maplist.size() - 1);
						senddata(maplist);
					}else{
						senddata(maplist);
					}
				}
			}
		});
	}
	
	private void senddata(ArrayList<String> datalist) {
		MyTask myTask = new MyTask();
		myTask.execute("www.xinlang.com");
	}
	
	class MyTask extends AsyncTask<String, Integer, String>{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
//			mFrame.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected String doInBackground(String... params) {
			//ϵͳ�������������߳�
			UploadImage uload = new UploadImage();
			String upload = uload.upload(maplist,name,money,content);
			return upload;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			int in = values[0];
//			mBar.setProgress(in);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(null != result && !result.equals("false")){
				Toast.makeText(MyfaqichildActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
				intent.putExtra("img", maplist.get(0));
				intent.putExtra("name", name);
				intent.putExtra("money", money);
				intent.putExtra("content", content);
				intent.putExtra("id", result);
				setResult(667, intent);
				finish();
			}else{
				Toast.makeText(MyfaqichildActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
			}
//			mFrame.setVisibility(View.GONE);
//			mTextView.setText(result);
		}
		
	}
	
	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, final int parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
	                Intent i = new Intent(
	   				Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	   				startActivityForResult(i, 1);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}
	
	/**
	  * ����û������ʱ���ʾ��ʽ�����ص�ǰʱ��ĸ�ʽ �����yyyyMMdd��ע����ĸy���ܴ�д��
	  * 
	  * @param sformat
	  *            yyyyMMddhhmmss
	  * @return
	  */
	public static String getUserDate(String sformat) {
	  Date currentTime = new Date();
	  SimpleDateFormat formatter = new SimpleDateFormat(sformat);
	  String dateString = formatter.format(currentTime);
	  return dateString;
	}
	
	private void photo() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(photoPath);
		if (!file.exists()) { 
			file.mkdir(); 
		}
		String stringDate = getUserDate("yyyyMMddhhmmss");
		photoName = photoPath + stringDate+".jpg";
		File photo = new File(photoName);
		imageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
		startActivityForResult(intent, PHOTO_CAPTURE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String sdStatus = Environment.getExternalStorageState();
		if (resultCode == RESULT_OK && requestCode == 1) {  
			 BitmapFactory.Options op = new BitmapFactory.Options();
				op.inSampleSize = 4; 
				ContentResolver resolver = getContentResolver();
					try {
						Uri originalUri = data.getData(); // ���ͼƬ��uri
						String[] proj = { MediaStore.Images.Media.DATA };
						Cursor cursor = managedQuery(originalUri, proj, null, null,null);
						// ���Ҹ������ ����ǻ���û�ѡ���ͼƬ������ֵ
						int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						// ���������ֵ��ȡͼƬ·��
						String path = cursor.getString(column_index);
						maplist.remove(maplist.size() - 1);
						maplist.add(path);
						if(maplist.size() < 4){
							maplist.add(stradd);
						}
						adapter.notifyDataSetChanged();
					} catch (OutOfMemoryError e) {
						Toast.makeText(MyfaqichildActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
					}
	        }if(requestCode == PHOTO_CAPTURE){
	        	if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
	        		
				} else {
					maplist.remove(maplist.size() - 1);
					maplist.add(photoName);
					if(maplist.size() < 4){
						maplist.add(stradd);
					}
					adapter.notifyDataSetChanged();
	        }
	    }
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if(maplist.size() <= 5){
			if(maplist.get(arg2).equals(stradd)){
				new PopupWindows(MyfaqichildActivity.this,1);
			}
		}
	}
}